package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dao.impl.EnquiryDaoimpl;
import com.entity.Comment;
import com.entity.PageBean;

// 前台留言
/**
 * Servlet implementation class GuestServlet
 */
@WebServlet("/GuestServlet/*")
public class GuestServlet extends BaseServlet {
	EnquiryDaoimpl eim = new EnquiryDaoimpl();

	// 留言
	protected void findse(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = (String) request.getSession().getAttribute("name");
		if (name != null) {
			request.setAttribute("flo", name);
			request.setAttribute("cf", "disabled=true");
		}

		String p = request.getParameter("p");

		int intp = 1;
		if (p != null) {
			intp = Integer.parseInt(p);
		}
		try {
			int coun = eim.secon();
			PageBean pagebean = new PageBean();
			pagebean.setSize(3);
			pagebean.setTotal(coun);
			pagebean.setCurpage(intp);
			List list = eim.enfind(intp);
			HttpSession session = request.getSession();
			session.setAttribute("se", intp);
			request.setAttribute("pagdata", list);// 请求里面放数据
			request.setAttribute("pagebean", pagebean);// 把总页数request
			request.getRequestDispatcher("/frontend/guestbook.jsp").forward(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 添加留言
	protected void addComment(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, SQLException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String name = (String) request.getSession().getAttribute("name");
		if (name == null) {
			response.sendRedirect("/Ebuy/frontend/login.jsp");
		} else {
			String title = request.getParameter("guestTitle");// 标题
			String content = request.getParameter("guestContent");// 内容
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String createtime = sdf.format(new Date());
			SimpleDateFormat hf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String reptime = hf.format(new Date());
			Comment com = new Comment(title, createtime, content, reptime, name);
			HttpSession session = request.getSession();
			int page = (int) session.getAttribute("se");
			int add = eim.addenq(com);
			if (add > 0) {
				response.sendRedirect("/Ebuy/GuestServlet/findse?p=" + page);
			} else {
				PrintWriter out = response.getWriter();
				out.print("<script>alert('提交失败！');location.href='/Ebuy/GuestServlet/findse'</script>");
			}
		}
	}

}
